// +build linux

package main

import (
	"io/ioutil"
	"os"
	"os/signal"
	"syscall"
)

func GetExitAction() func() {
	return func() {
		if err := syscall.Kill(syscall.Getpid(), syscall.SIGTERM); err != nil {
			log.Fatal("error when shutdown %v", err)
		}
	}
}

func GetRestartAction() func() {
	return func() {
		if err := syscall.Kill(syscall.Getpid(), syscall.SIGUSR2); err != nil {
			log.Fatal("error when restart %v", err)
		}
	}
}

func Wait() error {
	term_sys := make(chan os.Signal)
	forked := false
	signal.Notify(term_sys, syscall.SIGTERM, syscall.SIGUSR2, syscall.SIGQUIT, syscall.SIGINT)
	for {
		sig := <-term_sys
		switch sig {
		case syscall.SIGUSR2:
			if forked {
				return nil
			}
			forked = true
			if err := ForkExec(); nil != err {
				return err
			}
		default:
			log.Info("Received SIGTERM, exiting gracefully...")
			return nil
		}
	}
}

func KillParent(ppid int) error {
	return syscall.Kill(ppid, syscall.SIGQUIT)
}

func KillSelf(pid int, sig syscall.Signal) error {
	return syscall.Kill(pid, syscall.SIGQUIT)
}

func ReadTcpFile() ([]byte, error) {
	return ioutil.ReadFile(`/proc/net/tcp`)
}
